package br.com.rotary.servlet;

import br.com.rotary.modelo.Anexo;
import br.com.rotary.servico.AnexoServico;
import br.com.rotary.utilitario.ArquivoUtilitario;
import br.com.rotary.utilitario.Base64;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author laverson
 */
@WebServlet(name = "AnnexShowServlet", urlPatterns = "/show/*")
public class AnnexShowServlet extends HttpServlet {

    @EJB
    AnexoServico anexoService;
    private static final String filePath = "/media/images/imageJPG.png";
    private static final String fileExtension = ".png";
    private static final long serialVersionUID = 201011231103L;
    private ArquivoUtilitario arquivoUtilitario;

    public AnnexShowServlet() {
        super();
        arquivoUtilitario = new ArquivoUtilitario();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        OutputStream out;
        System.err.println("SEVLET");
        try {
            String id = request.getParameter("annex");
            String content = request.getParameter("annexContent");

            if (id != null) {
                try {
                    Anexo anexo = anexoService.pesquisar(Long.parseLong(id));

                    if (anexo.getArquivo() != null) {
                        anexo = arquivoUtilitario.gravarAnexos(anexo);
                        anexo.setArquivo(null);
                        anexoService.atualizar(anexo);
                    }

                    out = response.getOutputStream();
                    response.setContentType(anexo.getTipo());

                    String url = anexo.getUrl().concat(anexo.getNome());

                    url = url.replaceAll("[ãâàáä]", "?")
                            .replaceAll("[êèéë]", "?")
                            .replaceAll("[îìíï]", "?")
                            .replaceAll("[õôòóö]", "?")
                            .replaceAll("[ûúùü]", "?")
                            .replaceAll("[ÃÂÀÁÄ]", "?")
                            .replaceAll("[ÊÈÉË]", "?")
                            .replaceAll("[ÎÌÍÏ]", "?")
                            .replaceAll("[ÕÔÒÓÖ]", "?")
                            .replaceAll("[ÛÙÚÜ]", "?")
                            .replace('ç', '?')
                            .replace('Ç', '?')
                            .replace("[ñǹń]", "?")
                            .replace("[ÑŃǸ]", "?");

                    response.getOutputStream().write(Files.readAllBytes(Paths.get(url)));

                } catch (NumberFormatException numberFormatException) {

                    out = response.getOutputStream();
                    response.setContentType(".jpg");
                    response.getOutputStream().write(Files.readAllBytes(Paths.get(id)));
                }
            } else if (content != null) {

                out = response.getOutputStream();
                response.setContentType("image/jpg");
                response.getOutputStream().write(Base64.decode(content));

            } else {

                out = response.getOutputStream();

                response.setContentType(fileExtension);
                response.getOutputStream().write(Files.readAllBytes(Paths.get(request.getServletContext().getRealPath(filePath))));
            }

            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
            System.err.println(e);
        }
    }
}
